const fs = require('fs');
const path = require('path');
const { compatibilityTree } = require('../src/compatibility-tree');

// 旧文件迁移器
class LegacyMigrator {
  constructor() {
    this.baseDir = process.cwd();
  }

  // 执行完整迁移
  async migrateAll() {
    console.log('Starting legacy files migration...');
    
    await this.migrateConfigFiles();
    await this.migrateTestFiles();
    await this.migrateStaticFiles();
    
    console.log('Legacy files migration completed!');
  }

  // 迁移配置文件
  async migrateConfigFiles() {
    const configs = [
      { src: '.vscode', dest: '.config/vscode/latest' },
      { src: '.eslintrc.json', dest: '.config/eslint/latest' },
      { src: '.prettierrc.json', dest: '.config/prettier/latest' }
    ];

    for (const config of configs) {
      await this.safeMove(config.src, config.dest);
    }
  }

  // 迁移测试文件
  async migrateTestFiles() {
    const modules = ['core', 'adapters', 'platform', 'wasm'];
    
    for (const module of modules) {
      const srcDir = path.join('test', module);
      if (fs.existsSync(srcDir)) {
        const version = compatibilityTree.treeStructure.code[module];
        const destDir = path.join('test', module, version);
        await this.safeMove(srcDir, destDir);
      }
    }
  }

  // 迁移静态文件
  async migrateStaticFiles() {
    await this.safeMove('proto', 'compatibility-layer/proto');
    await this.safeMove('assets', 'compatibility-layer/assets');
  }

  // 安全的移动/复制操作
  async safeMove(src, dest) {
    const srcPath = path.join(this.baseDir, src);
    const destPath = path.join(this.baseDir, dest);

    if (!fs.existsSync(srcPath)) return;

    // 确保目标目录存在
    fs.mkdirSync(path.dirname(destPath), { recursive: true });

    // 移动文件/目录
    try {
      fs.renameSync(srcPath, destPath);
      console.log(`Moved ${src} -> ${dest}`);
    } catch (err) {
      // 回退到复制
      this.copyRecursiveSync(srcPath, destPath);
      console.log(`Copied ${src} -> ${dest} (move failed)`);
    }
  }

  // 递归复制
  copyRecursiveSync(src, dest) {
    if (fs.lstatSync(src).isDirectory()) {
      fs.mkdirSync(dest, { recursive: true });
      fs.readdirSync(src).forEach(item => {
        this.copyRecursiveSync(
          path.join(src, item),
          path.join(dest, item)
        );
      });
    } else {
      fs.copyFileSync(src, dest);
    }
  }
}

// 执行迁移
new LegacyMigrator().migrateAll().catch(console.error);